const Service = require("egg").Service;
const ejs = require("ejs");

class TemplateService extends Service {
  replaceVariable(str,data){
    const handle = new Function("$", `return  ${str}`);
    return handle(data)
  }
  renderTemplate(str,data){
   return ejs.render(str,data)
  }
  replaceJSONVariable(json, data) {
    
    function replaceOneWithTwo(obj, cb) {
      // 如果是对象，遍历对象的每个属性
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === "object" && obj[key] !== null) {
            // 如果属性值是对象或数组，递归调用函数
            replaceOneWithTwo(obj[key], cb);
          } else if (typeof obj[key] === "string") {
            const str = obj[key];
            if (str.startsWith("$.")) {
              const handle = new Function("$", `return  ${str}`);
              obj[key] = handle(data);
            }
          }
        }
      }
    }
    replaceOneWithTwo(json);
    return json;
  }
}
module.exports = TemplateService;
